<template>
  <div class="wrap">
    <div class="content">
      <div class="step-content" v-show="step === 1">
        <h4>1.添加本次发货计划的货件单</h4>

        <div>
          <!--    一件代发      -->
          货件类型：

          <el-button
            v-for="item in shipmentTypeList"
            :key="item.shipmentType"
            class="mgb10"
            size="medium"
            :type="currentShipmentType === item.shipmentType ? 'primary' : ''"
            @click="changeShipmentType(item.shipmentType)"
            :disabled="loading"
          >
            {{item.text}}
            <template v-if="item.shipmentType === shipmentType.oneStock">
              <el-tooltip class="item" effect="dark" placement="top">
                <template #content>{{ $t('shipment.仓库一件代发贴单使用的库存') }}</template>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <template v-else-if="item.shipmentType === shipmentType.middleStock">
              <el-tooltip class="item" effect="dark" placement="top">
                <template #content>{{ $t('shipment.暂存在物流商仓库，后续中转到官方仓仓库的库存，代贴单不会扣减该库存') }}</template>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <template v-else-if="item.shipmentType === shipmentType.mkdFull">
              <el-tooltip class="item" effect="dark" placement="top">
                <template #content>{{ $t('shipment.直送官方仓的货件，不计入物流商仓库库存',{name: getMercadoName()}) }}</template>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <template v-else-if="item.shipmentType === shipmentType.mkdFullCBT">
              <el-tooltip class="item" effect="dark" placement="top">
                <template #content>{{ $t('shipment.直送官方仓的货件，不计入物流商仓库库存',{name: getMercadoName()}) }}</template>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
            <template v-else-if="item.shipmentType === shipmentType.offlineDelivery">
              <el-tooltip class="item" effect="dark" placement="top">
                <template #content>送达海外后线下配送至私人地址的货件，不计入物流商仓库库存</template>
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>
          </el-button>


        </div>

        <div v-if="warehouseListFilter.length > 1 && false">
          收件仓库：
          <el-button
            class="mgb10"
            size="medium"
            v-for="warehouse in warehouseListFilter"
            :key="warehouse.warehouseId"
            :type="warehouse.warehouseId === currentForm.warehouseId ? 'primary' : ''"
            @click="selectWarehouse(warehouse)"
          >
            {{ warehouse.warehouseName }}
          </el-button>

        </div>

        <div v-if="currentShipmentType === shipmentType.mkdFullCBT || currentShipmentType === shipmentType.mkdFull">
          <div class="f14">
            {{ $t('table.warehouse') }}:
            <el-button
              v-for="item in showWarehouseList"
              :key="item.id"
              :type="currentForm.officialWarehouseId === item.id ? 'primary' : ''"
              @click="changeWarehouseId(item.id)"
              :disabled="loading"
            >
              {{ item.showName}}
            </el-button>
          </div>
        </div>

        <div v-if="showAccountList.length > 1">
          <div class="f14">
            店铺：
            <el-button
              v-for="item in showAccountList"
              :key="item.id"
              :type="currentForm.ogAccountId === item.id ? 'primary' : ''"
              @click="changeAccountId(item.id)"
              :disabled="loading"
            >
              {{ item.showName }}
            </el-button>
          </div>
        </div>

        <div>
          <div>
            <div>
              <div class="step-tips">
                <div style="display: inline;font-size: 14px">
                  <div class="mgr10" style="display: inline-block">
                    {{$t('shipment.step2Tips4')}}：<span class="font-blue">{{currentSkuNum}}</span>
                  </div>
                  <div style="display: inline-block">
                    {{$t('shipment.step2Tips5')}}：<span class="font-blue">{{currentGoodsNum}}</span>
                  </div>
                </div>

              </div>
              <div class="search mgt20">
                <div style="display: inline-block" class="mgr20" v-if="platformList.length > 1 && (currentShipmentType === shipmentType.oneStock || currentShipmentType === shipmentType.offlineDelivery)">
                  <el-select v-model="goodsParams.platformType" placeholder="请选择" @change="searchGoods">
                    <el-option label="全部平台" value=""></el-option>
                    <el-option
                      v-for="item in platformList"
                      :key="item.label"
                      :label="item.name"
                      :value="item.label">
                    </el-option>
                  </el-select>
                </div>


                <el-input
                  v-model="inputKeyword"
                  :placeholder="$t('common.searchForCompleteListingIDorSKU')"
                  style="width: 250px; margin-right: 10px; margin-bottom: 10px"
                  @keyup.enter.native="searchGoods()"
                  clearable
                  @clear="searchGoods()"
                >
                </el-input>
                <el-button size="small" type="primary" @click="searchGoods()">{{$t('common.search')}}</el-button>

                <export-goods-data
                  style="display: inline-block" class="mgl10"
                  :shipment-type="currentShipmentType"
                  @uploadsGoodsExcelSuccess="uploadsGoodsExcelSuccess"
                ></export-goods-data>
              </div>
            </div>
          </div>

          <div class="goods-table" >

            <!-- 仓库商品 -->
            <el-table
              border
              :data="currentGoodsList"
              v-loading="loading"
              :span-method="objectSpanMethod"
              :key="currentShipmentType"
              v-tableHeight="{bottomOffset: 80}"
              height="100px"
              ref="goodsTableDataTwo"
            >
              <el-table-column
                prop="image"
                :label="$t('table.productCover')"
                align="center"
                width="120"
                fixed="left"
              >
                <template slot-scope="{row}">
                  <div class="img-box img-one">
                    <img :src="row.image" alt="">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="title"
                :label="$t('table.title')"
                align="left"
                min-width="300"
              >
                <template slot-scope="{row}">
                  {{row.title}}
                  <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.ListingIDAndSKU')"
                align="left"
                min-width="200"
              >
                <template slot="header">
                  <span>{{$t('table.ListingIDAndSKU')}}</span>
                  <el-tooltip class="item" effect="dark" placement="top">
                    <template #content>
                      <div>Listing ID （SKU）行填写发货数量则表示本次发货的商品已贴对应的官方产品标（MLCode）</div>
                      <div>系统标（SKU）行填写发货数量则代表本次发货的商品已贴系统生成的产品标（SKU）</div>
                      <div>未贴标（SKU）行填写发货数量则代表本次发货的商品尚未贴产品标</div>
                    </template>
                    <i class="el-icon-question" style="color:#409eff; margin-left:5px;"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="{row}">
                  <template v-if="row.isTB">
                    <span class="font-red">
                      {{$t('shipment.Not labeled')}} {{row.sku ? `(${row.sku})` : ''}}
                    </span>
                  </template>
                  <template v-else-if="row.isSystem">
                    {{$t('shipment.System label')}} ({{row.sku}})
                  </template>
                  <template v-else>
                    {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
                  </template>
                </template>
              </el-table-column>
              <m-l-code-column></m-l-code-column>
              <el-table-column
                prop="weight"
                :label="$t('table.SKU重量与尺寸')"
                min-width="150"
                align="left"
              >
                <template v-slot="{row}">
                  <goods-size-v2
                    :goods-row="row"
                    :suit-id="row.suitId"
                    @saveGoodsSizeV2="finishGoodsSize(row)"
                  ></goods-size-v2>
                </template>
              </el-table-column>
              <goods-value-column
                :id="'suitId'"
                @successGoodsValue="updateGoodsValue"
                v-if="false"
              ></goods-value-column>

              <el-table-column
                label="箱规"
                prop="boxAttr"
                min-width="150"
              >
                <template v-slot="{row}">
                  <goods-box-size :suit-id="row.suitId" :goods-row="row.boxAttr" @saveGoodsBox="updateBoxSize"></goods-box-size>
                </template>
              </el-table-column>

              <el-table-column
                :label="$t('table.是否需要组装')"
                align="center"
                width="120"
                prop="isCombination"
                v-if="showCombination"
              >
                <template v-slot="{row}">
                  <el-switch
                    v-model="row.isCombination"
                    @change="changeIsCombination(row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.预计入库数量（整箱/箱）')"
                width="200"
                prop="exGoodsNumBox"
                fixed="right"
              >
                <template slot="header">
                  <span>{{$t('table.预计入库数量（整箱/箱）')}}</span>
                  <el-tooltip class="item" effect="dark" placement="top" content="一个货箱一种产品，当前产品整箱的箱数，每箱产品数量为箱装数">
                    <i class="el-icon-question" style="color:#409eff; margin-left:5px;"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="{row}">
                  <el-tooltip
                    :disabled="canEditBoxNum(row)"
                    content="编辑箱规后可填写"
                    placement="top"
                  >
                    <el-input-number
                      :step="1"
                      :precision="0"
                      :min="0"
                      :disabled="!canEditBoxNum(row)"
                      v-model="row.exGoodsNumBox"
                      @change="changeWareGoods(row);makeMoveWarehouseBoxList()"
                    >
                    </el-input-number>
                  </el-tooltip>

                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.expectedReceiptQuantityMix')"
                width="200"
                prop="exGoodsMixinNum"
                fixed="right"
                v-if="showMixinGoodsNum && currentShipmentType !== shipmentType.middleStock"
              >
                <template #header>
                  <span>{{$t('table.expectedReceiptQuantityMix')}}</span>
                  <el-tooltip class="item" effect="dark" placement="top" content="一个货箱多种产品，当前产品在所有混装货箱的总数量，个数">
                    <i class="el-icon-question" style="color:#409eff; margin-left:5px;"></i>
                  </el-tooltip>
                </template>
                <template slot-scope="{row}">
                  <el-input-number
                    :step="1"
                    :precision="0"
                    :min="0"
                    v-model="row.exGoodsMixinNum"
                    :disabled="row.isGoods && !row.inventoryId"
                    @change="changeWareGoods(row);clearMixinBoxGoodsList()"
                  >
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('预计入库总数量')"
                width="150"
                prop="exSumGoodsNum"
                fixed="right"
              >
                <template slot-scope="{row}">
                  {{row.exGoodsMixinNum + row.exGoodsNumBox * row.goodsNumInBox}}
                </template>
              </el-table-column>


            </el-table>


            <div class="page-wrap">
              <el-pagination
                background
                layout="total, prev, pager, next, jumper"
                :current-page.sync="goodsParams.page"
                :page-size="goodsParams.pageSize"
                :total="total"
                @current-change="getShipmentGoodsList"
              >
              </el-pagination>
            </div>
          </div>
          <div class="step-tips">
            {{$t('shipment.step2Tips6')}}
            <br>
            {{ $t('shipment.v2Step2Tips1') }}
            <br>
            <span class="font-red">
              {{$t('shipment.货件入库前必须贴好SKU标。如果发送未贴标的商品，仓库将帮您手动贴标入库，并收取额外的贴标费用，您可在“贴标工单”处查看详情')}}
            </span>
          </div>
        </div>


      </div>

      <div class="step-content" v-show="step === 2">
        <add-shipment-step2
          :choose-goods-list="chooseGoodsList"
          :choose-ware-goods-list="chooseWareGoodsList"
          :current-form="currentForm"
          :current-shipment-type="currentShipmentType"
          :show-combination="showCombination"
          :show-mixin-goods-num="showMixinGoodsNum"
        >
        </add-shipment-step2>
      </div>

      <div class="step-content" v-show="step === 3">
        <template v-if="planForm.type === 'first_leg'">
          <add-shipment-step3
            :mixin-box-goods-list="mixinBoxGoodsList"
            :choose-ware-goods-mixin-list="chooseWareGoodsMixinList"
            :mixin-box-arr="mixinBoxArr"
            :confirm-num="confirmNum"
            :wait-confirm-num="waitConfirmNum"
          ></add-shipment-step3>
        </template>
        <template v-else-if="planForm.type === PLAN_TYPE_MW()">
          <add-shipment-step3-m-w
            :move-warehouse-box-list="moveWarehouseBoxList"
            :mixin-box-goods-list="mixinBoxGoodsList"
            :choose-ware-goods-mixin-list="chooseWareGoodsMixinList"
            :mixin-box-arr="mixinBoxArr"
            :confirm-num="confirmNum"
            :wait-confirm-num="waitConfirmNum"
            :plan="planForm"
          ></add-shipment-step3-m-w>
        </template>


      </div>

      <div class="step-content" v-show="step === 4">
        <h4>4. 确认最终货件信息</h4>

        <el-card class="box-card ">
          <div class="line">
            <div class="label">{{ $t('table.shipmentType') }}：</div>
            <div class="item">
              {{getShipmentTypeStr2(currentShipmentType)}}
            </div>
          </div>


          <div class="line">
            <div class="label">预计发货SKU（种）：</div>
            <div class="item">{{ currentSkuNum }}</div>
            <div class="label mgl20">预计发货箱子总数：</div>
            <div class="item">{{ sumBoxNum }}</div>
            <div class="label mgl20">预计发货商品总数：</div>
            <div class="item">{{ currentGoodsNum }}</div>
          </div>
          <template v-if="false">
            <div class="line">
              <div class="label">{{$t('shipment.总货值（元）')}}：</div>
              <div class="item">{{sumGoodsValue}}</div>
            </div>
            <div class="line">
              <div class="label">{{$t('table.上架费用（元）')}}</div>
              <div class="item">{{sumListingFees}}</div>
            </div>
          </template>

        </el-card>
        <div class="storageForm">
         <h4>货件详情：</h4>
          <el-table
            border
            :data="boxTableData"
            style="width: 1000px"
          >
            <el-table-column
              prop="boxType"
              :label="$t('table.箱子规格')"
              align="center"
            >
              <template v-slot="{row}">
                <template v-if="row.boxType === 1">
                  {{$t('shipment.below150')}}
                </template>
                <template v-else-if="row.boxType === 2">
                  {{$t('shipment.above150')}}
                </template>
                <template v-else-if="row.boxType === 4">
                  {{ $t('shipment.整箱') }}
                </template>
                <template v-else-if="row.boxType === 5">
                  {{ $t('shipment.混箱') }}
                </template>
                <template v-else-if="row.boxType === 6">
                  {{ $t('shipment.直发箱') }}
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="boxNum"
              label="箱子数量"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="goodsNum"
              label="商品数量"
              align="center"
            ></el-table-column>
            <template v-if="planForm.type === PLAN_TYPE_FL()">
              <el-table-column
                prop="volumeWeight"
                label="体积重"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="squareNumber"
                label="方数"
                align="center"
              ></el-table-column>
            </template>


          </el-table>

          <div class="step-tips">
            保存或确认后将按照此处箱子数量生成对应的箱唛
            <span class="font-blue" style="cursor: pointer" @click="showShipmentBoxImage" v-if="false">{{$t('shipment.v2Step4Text4')}}</span>
            <el-image
              v-show="false"
              ref="shipmentBoxImage"
              :preview-src-list="[
                shipmentBoxImage
              ]"
            >
            </el-image>
          </div>
        </div>

        <div v-if="planForm.type === PLAN_TYPE_FL()">
          <div class="mgt20">
            <span style="font-weight: bold">报关方式：</span>
            <el-radio-group v-model="currentForm.BGMethod">
              <el-radio v-for="item in allBGMethodList" :key="item" :label="item">{{getShipmentBGMethodStr(item)}}</el-radio>
            </el-radio-group>
          </div>

          <div class="mgt20" v-if="currentShipmentType === shipmentType.offlineDelivery">
            <div>
              <span style="font-weight: bold">配送地址：</span>
              <choose-address :choose-id="currentForm.addressId" @submitAddress="chooseAddress" style="display: inline-block"></choose-address>
            </div>
            <div v-if="currentForm.address">
              <address-box :address="currentForm.address"></address-box>
            </div>
          </div>

        </div>

        <div v-if="isShipmentFullType" class="full-shipment-box mgt20">
          <div class="full-shipment-id mgb20">
            <div class="title">
              货件ID <el-input placeholder="请填写本次送仓的货件ID" v-model="currentForm.fullShipmentId" style="width: 300px" class="mgl10"></el-input>
            </div>

          </div>

          <div class="mgb20">
            <div class="title">上传箱标</div>
            <div class="sub-title">请上传本次送仓箱子的对应的美客多箱标，以供仓库下载应对特殊情况使用</div>
            <upload-file
              action="/shipmentV2/uploadFile"
              :file="currentForm.boxPDF"
              upload-file-text="上传箱标"
              edit-file-text="修改箱标"
              @uploadFileSuccess="uploadBoxPDFSuccess"
            ></upload-file>
          </div>

          <div class="mgb20">
            <div class="title">预约信</div>
            <div class="sub-title">本土店铺如由卖家预约送仓，请上传预约信。跨境店铺请忽略</div>
            <upload-file
              action="/shipmentV2/uploadFile"
              :file="currentForm.appointmentPDF"
              upload-file-text="上传预约信"
              edit-file-text="修改预约信"
              @uploadFileSuccess="uploadAppointmentPDFSuccess"
            ></upload-file>
          </div>
        </div>



        <div class="remark">
          <h4 v-if="false">
            {{$t('shipment.step4Text8')}}：
            <el-date-picker
              v-model="currentForm.estimateTime"
              type="date"
              :placeholder="$t('shipment.step4Text9')"
              value-format="yyyy-MM-dd"
            >
          </el-date-picker>
          </h4>

        </div>
        <div class="remark">
          <h4>{{$t('shipment.step4Text10')}}：</h4>
          <el-input
            type="textarea"
            style="width: 1500px"
            :placeholder="$t('shipment.step4Text11')"
            v-model="currentForm.remark"
            autosize
          ></el-input>
        </div>

      </div>

      <div class="footer">
        <template v-if="step === 1">
          <el-button @click="back">{{$t('shipment.cancel')}}</el-button>
        </template>
        <template v-if="step !== 1">
          <el-button @click="backStep">{{$t('common.prev')}}</el-button>
        </template>
        <template v-if="step !== 4">
          <el-button @click="nextStep" type="primary">{{$t('shipment.next')}}</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="submitShipment(-1)"  :loading="submitLoading" v-if="false">{{$t('common.save')}}</el-button>

          <el-button type="primary" @click="submitShipment(0)" :disabled="submitDisable" v-if="false" :loading="submitLoading">{{$t('common.confirm')}}</el-button>

          <el-button type="primary" @click="submitShipment(1)" :loading="submitLoading">
            {{ $t('common.confirm') }}</el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import {getAllAccountList} from "@/api/account";
import {
  getAddShipmentData,
  getFullGoodsList,
  getShipmentAccountSkuNum,
  getShipmentGoods, getShipmentTableType,
  getWarehouseGoodsList, printShipmentBoxPDF,
  saveShipment
} from "@/api/shipment";
import {
  deepCopy,
  getFalabellaName,
  getMercadoName,
  getPlatformShortNameByAccountNum,
  getPlatformTextColor,
  getShopeeName,getSheinName,getTikTokName,getAliexpressName,
} from "@/utils";
import {calGoodsVolumeWeight, generateRandomString, getWareHouseName} from "@/utils/common";
import {saveSuitGoodsIsCombination, setGoodsNumInBox} from "@/api/stock";
import {jumpLabelOrderInfo} from "@/utils/jumpView";
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import MLCodeListColumn from "@/views/stock/components/MLCodeListColumn.vue";
import {EventBus, rechargeTips, rechargeTipsCode} from "@/utils/eventBus";
import GoodsSize from "@/views/stock/components/GoodsSize";
import GoodsValueColumn from "@/views/stock/components/GoodsValueColumn.vue";
import warehouseMixin from "@/views/shipment/mixin/warehouseMixin";
import GoodsSizeV2 from "@/views/stock/components/GoodsSizeV2.vue";
import ExportGoodsData from "@/views/shipment/components/ExportGoodsData.vue";
import {MW_TYPE_BC, PLAN_TYPE_FL, PLAN_TYPE_MW} from "@/utils/shippingPlan";
import AddShipmentStep2 from "@/views/shipment/components/addShipmentStep2.vue";
import AddShipmentStep3 from "@/views/shipment/components/addShipmentStep3.vue";
import {downloadShipmentBoxLabel, downloadShipmentSystemLabelGoods, saveShippingPlanShipment} from "@/api/shipmentV2";
import AddShipmentStep3Full from "@/views/shipment/components/addShipmentStep3Full.vue";
import {FULL_BOX} from "@/utils/boxLabel";
import AddShipmentStep3MW from "@/views/shipment/components/addShipmentStep3MW.vue";
import {getShipmentBGMethodStr, getShipmentTypeStr2} from "../../utils/shipment";
import GoodsBoxSize from "@/views/stock/components/GoodsBoxSize.vue";
import UploadFile from "@/views/shipment/components/UploadFile.vue";
import UploadMiddleFile from "@/views/middleWork/components/UploadMiddleFile.vue";
import ChooseAddress from "@/views/userAddress/components/ChooseAddress.vue";
import AddressBox from "@/views/shipment/components/AddressBox.vue";
import platformMixin from "@/views/shipment/mixin/platformMixin";

const shipmentType = {
  oneStock: 'one_shipping',
  middleStock: 'middle',
  mkdFull: 'mkd_full',
  mkdFullCBT: 'mkd_cbt_full',
  falaFull: 'fala_full',
  offlineDelivery: 'offline_delivery', // 线下配送
}

const fullType = {
  Local: 'LOCAL',
  CBT: 'CBT',
}

export default {
  name: "addShipment",
  components: {
    AddressBox,
    ChooseAddress,
    UploadMiddleFile,
    UploadFile,
    GoodsBoxSize,
    AddShipmentStep3MW,
    AddShipmentStep3Full,
    AddShipmentStep3,
    AddShipmentStep2, ExportGoodsData, GoodsValueColumn, MLCodeColumn,GoodsSizeV2 },
  mixins: [warehouseMixin, platformMixin],
  computed: {
    // 显示组装
    showCombination(){
      return !(this.currentShipmentType === shipmentType.mkdFull || this.currentShipmentType === shipmentType.mkdFullCBT || this.currentShipmentType === shipmentType.offlineDelivery)
    },
    submitDisable(){
      return this.currentForm.storageType1 === 0 && this.currentForm.storageType2 === 0 && this.currentForm.storageType3 === 0
    },
    // 总listing数
    totalListingNum(){
      const set = new Set();
      this.confirmGoodsList.forEach(item=>{
        if(item.goodsNum > 0){
          set.add(item.goodsId)
        }
      })
      return set.size
    },
    // 总sku数
    totalSkuNum(){
      let num = 0;
      this.confirmGoodsList.forEach(item=>{
        if(item.goodsNum > 0){
          num++;
        }
      })
      return num;
    },
    currentSkuNum(){
      const arr = []

      this.chooseWareGoodsList.forEach(item=>{
        arr.push(item.suitId)
      })

      const length = Array.from(new Set(arr)).length
      if(length > 100){
        this.$errorMessage(this.$t('shipment.一次最多提交100个SKU种数，请删除部分SKU'))
      }
      return length
    },
    currentGoodsNum(){
      let num = 0;

      this.chooseWareGoodsList.forEach(item=>{
        const num1 = item.goodsNumInBox * item.exGoodsNumBox // 箱装数数量
        const num2 = item.exGoodsMixinNum
        if(num1){
          num += num1
        }
        if(num2){
          num += num2
        }
      })


      return num;
    },
    // 总货值
    sumGoodsValue(){
      let sum = 0;
      if(this.currentForm.type === 2){
        sum = this.chooseWareGoodsList.reduce((prev,item)=>{
          let num = 0
          const num1 = item.goodsNumInBox * item.exGoodsNumBox // 箱装数数量
          const num2 = item.exGoodsMixinNum
          if(num1){
            num += num1
          }
          if(num2){
            num += num2
          }
          return prev + (item.goodsValue * num)
        },0)
      }else{
        sum = this.chooseGoodsList.reduce((prev,item)=>{
          return prev + (item.goodsValue * item.exGoodsNum)
        },0)
      }
      return sum
    },
    // 商品总数量
    totalGoodsNum(){
      let num = 0;
      this.confirmGoodsList.forEach(item=>{
        num += item.goodsNum
      })
      return num;
    },
    // 店铺数量
    totalAccountNum(){
      const set = new Set();
      this.chooseWareGoodsList.forEach(item=>{
        if(item.ogAccountId){
          set.add(item.ogAccountId)
        }
      })
      return set.size
    },
    // 计算要合并的字段
    mergeCell(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'goodsNumInBox',
        'exTotalGoodsNum',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.currentGoodsList.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并


        if(item.suitId && item.suitId === this.currentGoodsList[index - 1].suitId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 整箱箱子数
    totalBoxNum(){
      let num = 0

      this.chooseWareGoodsList.forEach(item=>{
        if(item.exGoodsNumBox){
          num += item.exGoodsNumBox
        }
      })

      return num;
    },
    // 整箱商品数量
    totalBoxGoodsNum(){
      let num = 0
      this.chooseWareGoodsList.forEach(item=>{
        const num1 = item.goodsNumInBox * item.exGoodsNumBox
        if(num1){
          num += num1
        }
      })
      return num
    },
    // 混箱商品数量
    totalMixinGoodsNum(){
      let num = 0;
      this.chooseWareGoodsList.forEach(item=>{
        const num2 = item.exGoodsMixinNum
        if(num2){
          num += num2
        }
      })

      return num
    },
    // 显示的送仓仓库列表
    showWarehouseList(){
      return this.officialWarehouseList.filter(item => {
        return item.status === 1
      })
    },
    // 上架费用
    sumListingFees(){
      let fee = 0;
      if(this.currentShipmentType === shipmentType.oneStock){
        fee = this.chooseWareGoodsList.reduce((prev, item)=>{
          let num = 0;
          let volumeWeight = calGoodsVolumeWeight(item)
          let price = 0; // 当前的价格
          // 找到对应的价格
          this.shipmentOneWeightPrice.some(priceItem => {
            if(priceItem.weight <= volumeWeight){
              price = priceItem.price
              return false
            }else{
              return true;
            }
          })

          // 计算总共的数量
          const num1 = item.goodsNumInBox * item.exGoodsNumBox // 箱装数数量
          const num2 = item.exGoodsMixinNum
          if(num1){
            num += num1
          }
          if(num2){
            num += num2
          }
          return prev + price * num
        },0)
      }
      if(this.currentShipmentType === shipmentType.middleStock){
        fee = this.chooseWareGoodsList.reduce((prev, item)=>{
          let num = item.exGoodsNumBox; // 箱子数
          let volumeWeight = calGoodsVolumeWeight(item); // 单个商品的体积重
          volumeWeight = volumeWeight * item.goodsNumInBox; // 一个箱子的体积重
          let price = 0; // 计算的价格
          this.shipmentMiddleWeightPrice.some(priceItem => {
            if(priceItem.weight <= volumeWeight){
              price = priceItem.price
              return false
            }else{
              return true;
            }
          })
          return prev + price * num
        },0)
      }
      return fee;
    },
    warehouseListFilter(){
      return this.warehouseList.filter(item=>{
        const oneStock = this.currentShipmentType === shipmentType.oneStock; // 如果是一件代发返回一件代发的仓库
        if(oneStock){
          return item.roles.indexOf('oneShipping') !== -1
        }else{
          return item.roles.indexOf('middleTransfer') !== -1
        }
      })
    },
    // 可编辑的箱子类型 1: 整箱+混箱 2:仅整箱
    showMixinGoodsNum(){
      return this.shipmentTableType === 1
    },
    // 混装商品(仓库)
    chooseWareGoodsMixinList(){
      return this.chooseWareGoodsList.filter(item => item.exGoodsMixinNum > 0)
    },
    // 混装商品（官方仓）
    chooseGoodsMixinList(){
      return this.chooseGoodsList.filter(item => item.exGoodsMixinNum > 0)
    },
    // 待确认商品数量
    waitConfirmNum(){
      return this.totalMixinGoodsNum - this.confirmNum
    },
    // 已确认商品数量
    confirmNum(){
      return this.mixinBoxGoodsList.reduce((prev,curr)=>{
        return prev + curr.boxGoodsNum
      },0);
    },
    // 混箱箱子数量
    mixinBoxNum(){
      return this.mixinBoxArr.length
    },
    // 全部箱子数量
    sumBoxNum(){
      return this.totalBoxNum + this.mixinBoxNum
    },
    // 箱子表格数据
    boxTableData(){
      const arr = [
        {boxType: 4, boxNum: this.totalBoxNum, goodsNum: this.totalBoxGoodsNum, volumeWeight: this.totalBoxVolumeWeight, squareNumber: this.totalBoxSquareNumber},
        {boxType: 5, boxNum: this.mixinBoxNum, goodsNum: this.totalMixinGoodsNum,  volumeWeight: this.totalMixinBoxVolumeWeight, squareNumber: this.totalMixinBoxSquareNumber},
      ]
      return arr
    },
    showAccountList(){
      let arr = [];
      if(this.currentShipmentType === this.shipmentType.mkdFull){
        arr = this.allAccountList.filter(item => item.accountType === getMercadoName() && !item.isCBT)
      }
      else if(this.currentShipmentType === this.shipmentType.mkdFullCBT){
        arr = this.allAccountList.filter(item => item.accountType === getMercadoName() && item.isCBT)
      }
      return arr;
    },
    // 整箱的体积重
    totalBoxVolumeWeight(){
      let volumeWeight = 0;
      this.chooseWareGoodsList.forEach(item=>{
        if(item.goodsNumInBox > 0 && item.exGoodsNumBox > 0){
          const {length, width, height} = item.boxAttr
          volumeWeight += (length * width * height / 6000)
        }
      })
      return volumeWeight.toFixed(3)
    },
    // 整箱的方数
    totalBoxSquareNumber(){
      let num = 0;
      this.chooseWareGoodsList.forEach(item=>{
        if(item.goodsNumInBox > 0 && item.exGoodsNumBox > 0){
          const {length, width, height} = item.boxAttr
          num += (length * width * height / 1000000)
        }
      })
      return num.toFixed(5)
    },
    // 混箱的体积重
    totalMixinBoxVolumeWeight(){
      let num = 0;
      this.mixinBoxArr.forEach(boxIndex=>{
        const obj = this.mixinBoxGoodsList.find(mixinBox => mixinBox.boxIndex === boxIndex)
        if(obj){
          const {length, width, height} = obj.boxAttr
          num += (length * width * height / 6000)
        }
      })
      return num.toFixed(3)
    },
    // 混箱的方数
    totalMixinBoxSquareNumber(){
      let num = 0;
      this.mixinBoxArr.forEach(boxIndex=>{
        const obj = this.mixinBoxGoodsList.find(mixinBox => mixinBox.boxIndex === boxIndex)
        if(obj){
          const {length, width, height} = obj.boxAttr
          num += (length * width * height / 1000000)
        }
      })
      return num.toFixed(5)
    },
    // 是否官方仓类型
    isShipmentFullType(){
      return this.currentShipmentType === shipmentType.mkdFull || this.currentShipmentType === shipmentType.mkdFullCBT;
    },
  },
  data(){
    return {
      step: 1,
      currentShipmentType: shipmentType.oneStock,
      shipmentType: shipmentType,
      shipmentTypeList: [
        {shipmentType: shipmentType.oneStock, text: this.$t('shipment.oneStock')},
        {shipmentType: shipmentType.middleStock, text: '暂存中转'},
      ], // 货件单类型
      shipmentTableType: 1, // 1：整箱+混箱 2：仅混箱
      currentForm: {
        type: 2,
        goods: [],
        remark: '',
        estimateTime: '',
        subType: 1,
        mixinBoxNum: 0, // 混箱数量
        fullBoxNum: 0, // 直发箱数量
        fullType: fullType.Local,
        officialWarehouseId: 0, // 仓库对应的id
        warehouseId: 0,
        ogAccountId: 0,
        fullShipmentId: '', // 送仓id
        boxPDF: '', // 箱标
        appointmentPDF: '', // 预约信
        BGMethod: '',
        address: null, // 配送地址
        addressId: 0,
      },
      currentAccountId: 0, // 当前选择的店铺id
      accountList: [],
      allAccountList: [],
      goodsList1: [], // 官方仓商品
      goodsList2: [], // 美刻达商品
      confirmGoodsList: [], // 确认商品列表
      submitLoading: false,
      isSubmit: false,
      loading: false,
      inputKeyword: '',
      searchKeyword: '',
      goodsParams: {
        page: 1,
        pageSize: 10,
        platformType: '', // 平台
      },
      total:0,
      currentGoodsList: [],
      chooseGoodsList: [], // 选择的官方仓商品
      chooseWareGoodsList: [], // 选择的仓库商品
      is_search: false,
      goodsNumForm: {
        id: '',
        goodsNumInBox: 0,
      },
      shipmentBoxImage: require('@/assets/images/shipmentBox-image01.png'), // 示意图
      saveGoodsSizeIds: [], // 保证编辑之后的还能再编辑 定义一个数组记录所编辑过的id
      shipmentOneWeightPrice: [], // 一件代发 上架单价
      shipmentMiddleWeightPrice: [], // 中转送仓 上架单价
      goodsExcelDialog: false,
      downExcelLoading: false,
      uploadExcelLoading: false,
      warehouseList: [], // 收件仓库选择
      allBGMethodList: [], // 报关方式
      planForm: {
        planId: '',
        planName: '',
        type: PLAN_TYPE_FL,
        flWarehouseId: 0,
        warehouseId: 0,
        makeContainerType: 0, // 装柜方式
        transferType: '', // 运输类型
        deliverDate: '', // 预计送达时间
        moveWarehouseType: MW_TYPE_BC, // 移仓类型
        containerNo: '', // 货柜号
        haveLogisticsNo: true, // 是否有物流单号
      }, // 发货计划表单数据
      mixinBoxGoodsList: [], // 混装的箱子商品
      mixinBoxArr: [], // 混箱序号
      moveWarehouseBoxList: [], // 移仓的箱子
    }
  },
  created() {
    this.setPlanForm()
    this.setShipmentTypeList()
    // this.getAllAccountList()
    this.getBaseData();

  },
  updated () {
    this.$nextTick(() => {
      //this.$refs['goodsTableDataOne']?.doLayout();
      this.$refs['goodsTableDataTwo']?.doLayout();
      // this.$refs['goodsTableDataThree']?.doLayout();
      // this.$refs['goodsTableDataFour']?.doLayout();
      // this.$refs['goodsTableDataFive']?.doLayout();
    })
  },
  methods:{
    getShipmentBGMethodStr,
    PLAN_TYPE_FL() {
      return PLAN_TYPE_FL
    },
    getShipmentTypeStr2,
    PLAN_TYPE_MW() {
      return PLAN_TYPE_MW
    },
    getPlatformTextColor,
    getShopeeName,
    getPlatformShortNameByAccountNum,
    getFalabellaName,
    getMercadoName,
    getWareHouseName,
    setShipmentTypeList(){
      if(this.planForm.type === PLAN_TYPE_FL){
        this.shipmentTypeList.push(
          {shipmentType: shipmentType.mkdFull, text: this.$t('shipment.mercadoFullLocal',{accountType: getMercadoName()}) },
        )
        if(this.$store.getters.isAuthMKDCBT){
          this.shipmentTypeList.push(
            {shipmentType: shipmentType.mkdFullCBT, text: this.$t('shipment.mercadoFullCBT',{accountType: getMercadoName()})}
          )
        }
        this.shipmentTypeList.push(
          {shipmentType: shipmentType.offlineDelivery, text: '线下配送' },
        )
      }
    },
    setPlanForm(){
      const params = this.$route.params;
      if(Object.keys(params).length === 0){
        // 没有对应的发货计划参数...
        console.error('缺少参数')
        // this.$errorMessage('缺少参数')
        this.$router.go(-1)
        return

      }
      this.planForm = deepCopy(params)
      // 有些客户过来的时候 不知道为什么参数会缺失 返回让他们重新选择
      if(!this.planForm.planId){
        if(!this.planForm.warehouseId){
          this.$router.go(-1);
          console.error('缺少warehouseId')
          return;
        }
      }

    },
    // 获取需要的数据
    getBaseData(){
      getShipmentTableType({
        planId: this.planForm.planId,
        warehouseId: this.planForm.warehouseId,
      })
        .then(res=>{
          this.shipmentTableType = res.data.shipmentTableType
        })

      getAddShipmentData()
        .then(res=>{
          this.shipmentOneWeightPrice = deepCopy(res.data.shipmentOneWeightPrice)
          this.shipmentMiddleWeightPrice = deepCopy(res.data.shipmentMiddleWeightPrice)
          this.warehouseList = res.data.warehouseList
          this.warehouseList.some(item => {
            this.currentForm.warehouseId = item.warehouseId
            return true
          })
          this.changeShipmentTypeStep2(shipmentType.oneStock)
          this.allAccountList = deepCopy(res.data.accountList)
          this.allBGMethodList = deepCopy(res.data.BGMethodList)
          if(this.planForm.type === PLAN_TYPE_FL){
            this.currentForm.BGMethod = this.allBGMethodList[0]
          }
        })

      // 获取所有所有的仓库
      this.getOfficialWarehouseList();
    },
    finishWarehouseApi(){
      this.showWarehouseList.some(item=>{
        this.changeWarehouseId(item.id)
        return true;
      })
    },
    // 选择了某一个店铺
    chooseAccount(accountId){
      this.currentAccountId = accountId
      if(this.currentForm.type === 2){
        this.searchGoods()
      }
    },
    nextStep(){
      if(this.step === 1){
        if(!this.currentSkuNum || !this.currentGoodsNum){
          this.$errorMessage(this.$t('shipment.step2Tips7'))
          return;
        }
        const goodsValueSet = new Set()
        const goodsSizeSet = new Set()
        if(this.currentForm.type === 2){
          const sizeGoods = this.chooseWareGoodsList.filter(item=>{
            if(!item.weight){
              goodsSizeSet.add(item.sku)
              return true
            }
            return false
          })
          this.chooseWareGoodsList.forEach(item=>{
            if(!item.goodsValue){
              goodsValueSet.add(item.sku)
            }
          })
          if(goodsSizeSet.size > 0){
            let html = `<span class="font-bold">${this.$t('shipment.请完善以下SKU的重量信息')}：</span><br>`
            goodsSizeSet.forEach(item=>{
              html += `<br>SKU: ${item}`
            })
            this.$message({
              showClose: true,
              type: 'warning',
              dangerouslyUseHTMLString: true,
              message: html,
              duration: 0,
            });
            return;
          }
        }
        if(this.currentForm.type === 1){
          this.chooseGoodsList.forEach(item=>{
            if(!item.goodsValue){
              goodsValueSet.add(item.sku)
            }
          })
        }


        if(this.currentShipmentType === shipmentType.mkdFull || this.currentShipmentType === shipmentType.mkdFullCBT){
          // 如果当前类型是官方仓 需要选送仓的仓库
          if(!this.currentForm.officialWarehouseId){
            this.$errorMessage('请选择仓库')
            return;
          }
        }else{
          this.currentForm.officialWarehouseId = 0;
        }

      }
      // 第三步
      if(this.step === 2){
        // 没有混装 跳过第三步
        if(this.totalMixinGoodsNum === 0 && this.planForm.type === PLAN_TYPE_FL){
          this.step++
        }
        if(this.planForm.type === PLAN_TYPE_MW){
          // this.makeMoveWarehouseBoxList()
        }
      }
      // 第四步
      if(this.step === 3){
        if(this.waitConfirmNum > 0){
          this.$confirm('存在尚未确认的存放货箱的的混装商品，确认下一步将自动从当前货件单删除对应的混装商品', '确认下一步?')
            .then(res=>{
              // 如果还有未编辑的混装商品 清除对应的混装数量 清除混箱的商品
              this.clearWaitConfirmMixin()
              this.step++
            })
            .catch(res=>{

            })

          return;
        }
      }


      this.step++

    },
    backStep(){
      this.step--;
      if(this.step === 1){
        this.getShipmentGoodsList()
      }
    },
    // 获取所有的店铺
    getAllAccountList(){
      if(this.accountList.length){
        return;
      }
      this.loading = true
      getAllAccountList()
        .then(res=>{
          this.loading = false
          this.accountList = [];
          res.data.forEach(item=>{
            this.accountList.push({
              accountId: item.id,
              showName: item.showName,
              goodsNum: 0,
              accountType: item.accountType,
              accountTypeNum: item.accountTypeNum,
              fullGoodsNum: item.fullGoodsNum, // 官方仓商品数
            })
          })
          this.allAccountList = deepCopy(this.accountList)
          this.currentAccountId = this.accountList[0].accountId;
        })
    },
    // 根据当前的类型 输出对应的店铺
    changeAccountList(){
      // 第三方仓 所有店铺都显示
      if(this.currentForm.type === 2){
        this.accountList = deepCopy(this.allAccountList);
      }
      // 美客多的官方仓
      if(this.currentForm.type === 1){
        this.accountList = this.allAccountList.filter(item=>{
          return item.accountTypeNum === 1
        })
      }
      // falabella官方仓
      if(this.currentForm.type === 3){
        this.accountList = this.allAccountList.filter(item=>{
          return item.accountTypeNum === 2
        })
      }
      // 虾皮官方仓
      if(this.currentForm.type === 4){
        this.accountList = this.allAccountList.filter(item=>{
          return item.accountTypeNum === 3
        })
      }
      this.currentAccountId = this.accountList[0].accountId;
    },
    // 获取仓库商品
    getWareHouseGoods(){
      const params = deepCopy(this.goodsParams);
      params.keyword = this.inputKeyword
      params.ogAccountId = this.currentForm.ogAccountId
      // params.isWarehouse = this.currentForm.type === 2 && this.currentForm.subType === 1 ? 1 : 0;
      params.shipmentType = this.currentShipmentType
      params.warehouseId = this.currentForm.warehouseId
      this.loading = true
      getWarehouseGoodsList(params)
        .then(res=>{
          this.loading = false
          this.currentGoodsList = []
          this.total = res.info.total
          res.data.forEach(item=>{
            if(item.isSystem && this.currentForm.subType === 2){
              return
            }
            if(this.saveGoodsSizeIds.indexOf(item.id) !== -1){
              item.isLockSize = 0
            }
            item.exGoodsNumBox = 0; // 预计箱子数
            item.exGoodsMixinNum = 0; // 预计数量
            this.chooseWareGoodsList.some((wareGoods)=>{
              if(wareGoods.id === item.id){
                item.exGoodsNumBox = wareGoods.exGoodsNumBox
                item.exGoodsMixinNum = wareGoods.exGoodsMixinNum
                item.isCombination = wareGoods.isCombination
                return true
              }
            })
            item.editGoodsNumBoxStatus = 0; // 编辑状态
            item.editGoodsValueStatus = 0;

            this.currentGoodsList.push(item)
          })
        })
    },
    // 提交表单数据
    submitShipment(status = 0){
      if(!this.sumBoxNum){
        this.$errorMessage(this.$t('shipment.detailsText4'))
        return;
      }
      if(this.currentSkuNum > 100){
        this.$errorMessage(this.$t('shipment.一次最多提交100个SKU种数，请删除部分SKU'))
        return;
      }
      if(this.isShipmentFullType){
        if(!this.currentForm.fullShipmentId){
          this.$errorMessage('请填写货件ID')
          return;
        }
        // if(!this.currentForm.boxPDF){
        //   this.$errorMessage('请上传箱标')
        //   return;
        // }
      }
      if(this.currentShipmentType === shipmentType.offlineDelivery){
        if(!this.currentForm.address){
          this.$eMsg('请选择配送地址')
          return;
        }
      }
      const shipmentForm = {
        type: this.currentForm.type,
        subType: this.currentForm.subType,
        remark: this.currentForm.remark,
        estimateTime: this.currentForm.estimateTime,
        goods: this.chooseWareGoodsList,
        officialWarehouseId: this.currentForm.officialWarehouseId, // 选择的仓库
        mixinBoxGoodsList: this.mixinBoxGoodsList,
        moveWarehouseBoxList: this.moveWarehouseBoxList, // 移仓整箱的数据
        shipmentType: this.currentShipmentType,
        fullShipmentId: this.currentForm.fullShipmentId,
        boxPDF: this.currentForm.boxPDF,
        appointmentPDF : this.currentForm.appointmentPDF,
        ogAccountId: this.currentForm.ogAccountId,
        BGMethod: this.currentForm.BGMethod,
        address: this.currentForm.address,
      }
      const planForm = this.planForm
      const postData = {
        shipmentForm,
        planForm,
      }
      new Promise((resolve, reject)=>{
        let title = '确认提交货件信息?'
        let message = '货件信息提交后不可修改，请确保填写的信息无误'
        this.$confirm(message, title)
          .then(()=>{
            resolve()
          })
          .catch(()=>{
            reject()
          })
      })
        .then(()=>{
          this.submitLoading = true;
          saveShippingPlanShipment(postData)
            .then(res=>{
              this.isSubmit = true
              this.submitLoading = false
              if(res.error === rechargeTipsCode){
                EventBus.$emit(rechargeTips)
                return;
              }

              if(res.error === 0){
                // 弹出箱唛
                this.shipmentBoxLabel(res.data.shipmentId)
                this.goodsLabel(res.data.shipmentId)
                const planId = res.data.planId;
                const labelOrderId = res.data.labelOrderId;
                // 有贴标工单 跳转到贴标工单
                if(labelOrderId){
                  this.$router.push({
                    name: 'labelOrderInfo',
                    query: {
                      id: labelOrderId,
                    }
                  })
                }else{
                  // 跳转到发货计划页面
                  this.$router.push({
                    name: 'shippingPlanInfo',
                    query: {
                      id: res.data.planId
                    }
                  })
                }

              }else{
                this.$errorMessage(res.message)
              }
            })
            .catch(res =>{
              this.submitLoading = false
            })
        })
        .catch(()=>{})
    },
    shipmentBoxLabel(shipmentId){
      downloadShipmentBoxLabel(shipmentId)
        .then(res=>{
          if(res.type === 'application/json'){
            this.$message({
              message: '下载失败，请稍后再尝试',
              duration : 5000,
              type: 'error',
              showClose: true,
            });
            return;
          }

          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000)
        })
    },
    goodsLabel(shipmentId){
      downloadShipmentSystemLabelGoods(shipmentId)
        .then(res=>{
          if(res.type === 'application/json'){
            return;
          }

          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000)
        })
    },

    // 商品数量发生改变 添加/删除对应官方仓商品
    goodsNumChange(row){
      row.exGoodsMixinNum = row.exGoodsMixinNum ? row.exGoodsMixinNum : 0;
      row.exGoodsNumBox = row.exGoodsNumBox ? row.exGoodsNumBox : 0;
      row.goodsNumInBox = row.goodsNumInBox ? row.goodsNumInBox : 0;
      const add = row.exGoodsMixinNum > 0 || row.exGoodsNumBox * row.goodsNumInBox > 0
      const index = this.chooseGoodsList.findIndex(item=> item.suitId === row.suitId)
      if(add && index === -1){
        this.chooseGoodsList.push(row)
      }
      if(index !== -1 && !add){
        this.chooseGoodsList.splice(index,1)
      }
    },
    // 生成确认商品
    createConfirmGoods(){
      this.confirmGoodsList = [];
      const suitId = [];
      this.chooseGoodsList.forEach(item=>{
        if(item.goodsNum > 0){
          if(item.suitId !== 0 && suitId.indexOf(item.suitId) !== -1){
            return;
          }
          const obj = deepCopy(item);
          obj.listingList = [];
          obj.accountList = [];
          suitId.push(item.suitId)
          obj.suitSkuList.forEach(_item=> {
            const accountIndex = obj.accountList.findIndex(_account => _account.accountId === _item.accountId)
            if(accountIndex === -1){
              this.accountList.some(accountItem => {
                if(accountItem.accountId === _item.accountId){
                  obj.accountList.push({
                    accountId: accountItem.accountId,
                    showName: accountItem.showName,
                    accountTypeNum: accountItem.accountTypeNum,
                    accountType: accountItem.accountType,
                  })
                  _item.accountType = accountItem.accountType
                  _item.accountTypeNum = accountItem.accountTypeNum
                  _item.showName = accountItem.showName
                  return true
                }
              })
            }else{
              _item.accountType = obj.accountList[accountIndex].accountType
              _item.accountTypeNum = obj.accountList[accountIndex].accountTypeNum
              _item.showName = obj.accountList[accountIndex].showName
            }
          })

          this.confirmGoodsList.push(obj)
        }
      })
    },
    findAccountByAccountId(accountId){
      return this.accountList.find(item=> item.accountId === accountId)
    },
    back(){
      this.$router.go(-1)
    },
    // 获取店铺的数量
    getAccountSkuNum(){
      const params = {
        type: this.currentForm.type
      }
      getShipmentAccountSkuNum(params)
        .then(res=>{
          const data = res.data
          this.accountList.forEach(item=>{
            item.goodsNum = 0;
            data.some(_item=>{
              if(_item.accountId === item.accountId){
                item.goodsNum = _item.skuNum;
                return true;
              }
            })
          })
        })
    },
    searchGoods(){
      this.goodsParams.page = 1;
      this.getShipmentGoodsList()
    },
    getShipmentGoodsList(){
      // if(this.currentForm.type === 2){
        this.getWareHouseGoods() // 获取仓库商品
      // }else{
      //   this.getFullGoodsList() // 获取官方仓商品
      // }
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.getMergeCell(this.currentGoodsList)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.getMergeCell(this.chooseWareGoodsList)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    getMergeCell(list){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'goodsNumInBox',
        'exTotalGoodsNum',
        'goodsValue',
        'isCombination',
        'weight',
        'boxAttr',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      list.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并


        if(item.suitId && item.suitId === list[index - 1].suitId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 失去焦点提交表单
    submitGoodsNumForm(){
      this.currentGoodsList.some(item=>{
        if(item.suitId === this.goodsNumForm.id){
          const currentGoodsNumBox = this.goodsNumForm.goodsNumInBox
          item.editGoodsNumBoxStatus = 0
          if(currentGoodsNumBox !== item.goodsNumInBox && currentGoodsNumBox !== '' && !isNaN(parseInt(currentGoodsNumBox))){
            const data = {
              id: item.suitId,
              goodsNumInBox: currentGoodsNumBox
            }

            // 修改对应的数据
            this.currentGoodsList.filter(_item => _item.suitId === item.suitId ).forEach(_item => {
              _item.goodsNumInBox = Number(currentGoodsNumBox)
              if(_item.goodsNumInBox === 0){
                _item.exGoodsNumBox = 0
              }
              this.changeWareGoods(_item)
            });
            this.chooseWareGoodsList.filter(_item => _item.suitId === item.suitId ).forEach(_item => {
              _item.goodsNumInBox = Number(currentGoodsNumBox)
              if(_item.goodsNumInBox === 0){
                _item.exGoodsNumBox = 0
              }
            });


            item.goodsNumInBox = currentGoodsNumBox
            // 请求接口修改数据 但是不刷新表格
            setGoodsNumInBox(data)
              .then(res=>{
                console.log(res)
              })
          }

          return true;
        }
      })
    },
    // 编辑箱装数
    editGoodsNumBox(row){
      this.goodsNumForm.id = row.suitId
      this.goodsNumForm.goodsNumInBox = row.goodsNumInBox
      row.editGoodsNumBoxStatus = 1
      this.$nextTick(()=>{
        document.getElementById(row.id + 'goodsNumInBox').focus()
      })
    },
    // 编辑了仓库商品 添加或移除对应的仓库商品
    changeWareGoods(row){
      if(!row.exGoodsMixinNum){
        row.exGoodsMixinNum = 0
      }
      if(!row.exGoodsNumBox){
        row.exGoodsNumBox = 0
      }
      const add = row.exGoodsMixinNum > 0 || row.exGoodsNumBox * row.goodsNumInBox > 0
      const index = this.chooseWareGoodsList.findIndex(item => item.id === row.id)
      if(add){
        if(index === -1){
          const index2 = this.chooseWareGoodsList.findIndex(item => item.suitId === row.suitId)
          if(index2 === -1 || row.isTB || row.isSystem){
            this.chooseWareGoodsList.push(row)
          }else{
            this.chooseWareGoodsList.splice(index2,0,row)
          }
        }else{
          const currentRow = this.chooseWareGoodsList.find(item => item.id === row.id)
          currentRow.exGoodsMixinNum = row.exGoodsMixinNum
          currentRow.exGoodsNumBox = row.exGoodsNumBox
        }
      }else{
        if(index !== -1){
          this.chooseWareGoodsList.splice(index,1)
        }
      }
      // 数据排序 为了后面的单元格合并
      this.chooseWareGoodsList.sort((a,b)=>{
        return a.suitId - b.suitId
      })
    },
    // 改变了组装
    changeIsCombination(row){
      this.chooseWareGoodsList.filter(item => item.suitId === row.suitId)
        .forEach(item => {
          item.isCombination = row.isCombination
        })
      this.currentGoodsList.filter(item => item.suitId === row.suitId)
        .forEach(item => {
          item.isCombination = row.isCombination
        })

      saveSuitGoodsIsCombination({
        id: row.suitId,
        isCombination: row.isCombination,
      })
      .then(res=>{
      })

    },
    // 预计入库商品总数
    getExTotalGoodsNum(suitId){
      let num = 0
      this.chooseWareGoodsList.filter(item=> item.suitId === suitId)
        .forEach(item=>{
          const num1 = item.goodsNumInBox * item.exGoodsNumBox // 箱装数数量
          const num2 = item.exGoodsMixinNum
          if(num1){
            num += num1
          }
          if(num2){
            num += num2
          }
        })
      return num
    },
    // 获取官方仓的商品
    getFullGoodsList(){
      const params = deepCopy(this.goodsParams);
      params.keyword = this.inputKeyword
      params.ogAccountId = this.currentAccountId
      params.fullType = this.currentForm.fullType
      params.type = this.currentShipmentType
      params.warehouseId = this.currentForm.warehouseId
      this.loading = true
      getFullGoodsList(params)
        .then(res=>{
          this.loading = false
          this.currentGoodsList = []
          res.data.forEach(item=>{
            // item.exGoodsNum = 0;
            item.editGoodsValueStatus = 0;
            item.exGoodsNumBox = 0; // 预计箱子数
            item.exGoodsMixinNum = 0; // 预计数量
            item.editGoodsNumBoxStatus = 0; // 编辑状态
            this.chooseGoodsList.some(_choose =>{
              if(_choose.suitId === item.suitId){
                item.exGoodsNum = _choose.exGoodsNum
                item.exGoodsMixinNum = _choose.exGoodsMixinNum
              }
            })
            this.currentGoodsList.push(item)
          })
          this.total = res.info.total
        })
    },
    // 显示示意图
    showShipmentBoxImage(){
      this.$refs.shipmentBoxImage.clickHandler()
    },
    // 打印箱标
    printBox(id){
      printShipmentBoxPDF(id)
        .then(res=>{
          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );

          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000)
        })
    },
    // 切换货件类型
    changeShipmentType(type){
      if(type === this.currentShipmentType){
        return;
      }
      this.goodsParams.platformType = ''
      const haveGoods = this.chooseGoodsList.length > 0 || this.chooseWareGoodsList.length > 0

      new Promise((resolve, reject)=>{
        if(!haveGoods){
          resolve()
          return
        }
        let message = '切换类型将清除当前已编辑商品数据<br/>如还需为发货计划添加其他类型货件请点击下一步操作提交当前货件后再添加新的货件'
        this.$confirm(message, this.$t('shipment.确定切换货件类型？') , {
          dangerouslyUseHTMLString: true,
          type : 'warning',
        })
          .then(res=>{
            // 点击了确定
            resolve()
          })
          .catch(res=>{
            // 点击了取消
            reject()
          });
      })
        .then(()=>{
          this.changeShipmentTypeStep2(type)
        })

    },
    changeShipmentTypeStep2(type){
      this.chooseGoodsList = []
      this.chooseWareGoodsList = []
      this.currentShipmentType = type
      this.currentForm.ogAccountId = 0
      console.log(type)
      switch (type){
        case shipmentType.oneStock:
          this.currentForm.type = 2
          this.currentForm.subType = 1;
          break;
        case shipmentType.middleStock:
          this.currentForm.type = 2;
          this.currentForm.subType = 2;
          break;
        case shipmentType.mkdFull:
          this.currentForm.type = 1;
          this.currentForm.fullType = fullType.Local
          if(this.showAccountList.length > 0){
            this.currentForm.ogAccountId = this.showAccountList[0].id
          }
          break;
        case shipmentType.falaFull:
          this.currentForm.type = 3;
          break;
        case shipmentType.mkdFullCBT:
          this.currentForm.type = 7;
          this.currentForm.fullType = fullType.CBT
          if(this.showAccountList.length > 0){
            this.currentForm.ogAccountId = this.showAccountList[0].id
          }
          break;
      }
      this.warehouseListFilter.some(item=>{
        this.currentForm.warehouseId = item.warehouseId
        return true;
      })
      this.goodsParams.page = 1;
      this.getShipmentGoodsList()
    },
    //
    getGoodsSizeList(row){
      return this.currentGoodsList.filter(item => item.suitId === row.suitId)
    },
    // 编辑商品完成
    finishGoodsSize(row){
      this.saveGoodsSizeIds.push(row.id)
      this.chooseGoodsList.filter(item => item.suitId === row.suitId)
        .forEach(item=>{
          item.weight = row.weight
          item.width = row.width
          item.length = row.length
          item.height = row.height
        })
      this.currentGoodsList.filter(item => item.suitId === row.suitId)
        .forEach(item => {
          item.weight = row.weight
          item.width = row.width
          item.length = row.length
          item.height = row.height
        })
    },
    // 修改货值
    updateGoodsValue(row){
      if(this.currentForm.type === 2){
        const suitId = row.id
        this.currentGoodsList.forEach(item => {
            if(item.suitId === suitId){
              item.goodsValue = row.goodsValue
            }
          })
        this.chooseWareGoodsList.forEach(item => {
          if(item.suitId === suitId){
            item.goodsValue = row.goodsValue
          }
        })
      }
      if(this.currentForm.type === 1){
        const suitId = row.id
        this.currentGoodsList.forEach(item => {
          if(item.suitId === suitId){
            item.goodsValue = row.goodsValue
          }
        })
        this.chooseGoodsList.forEach(item => {
          if(item.suitId === suitId){
            item.goodsValue = row.goodsValue
          }
        })
      }
    },
    // 选择了对应的仓库
    changeWarehouseId(id){
      this.currentForm.officialWarehouseId = id
    },
    changeAccountId(id){
      this.currentForm.ogAccountId = id
      this.goodsParams.page = 1;
      this.getShipmentGoodsList()
    },
    // 解析数据成功
    uploadsGoodsExcelSuccess(data){
      if(this.currentShipmentType === shipmentType.middleStock){
        data = data.filter(item => !item.isSystem)
      }
      if(this.currentShipmentType === shipmentType.mkdFull || this.currentShipmentType === shipmentType.mkdFullCBT || this.currentShipmentType === shipmentType.offlineDelivery){
        data = data.filter(item => !item.isSystem && !item.isTB)
      }
      this.chooseWareGoodsList = data
      if(this.planForm.type === PLAN_TYPE_MW){
        this.makeMoveWarehouseBoxList()
      }
      this.nextStep()
    },
    selectWarehouse(warehouse){
      if(this.currentForm.warehouseId === warehouse.warehouseId){
        return;
      }
      const haveGoods = this.chooseGoodsList.length > 0 || this.chooseWareGoodsList.length > 0
      if(haveGoods){
        this.$warning(this.$t('切换仓库将清除当前已编辑商品数据'), {
          title: this.$t('确定切换收件仓库？'),
        })
          .then(res=>{
            // 点击了确定
            this.chooseGoodsList = []
            this.chooseWareGoodsList = []
            this.currentForm.warehouseId = warehouse.warehouseId
            this.searchGoods();
          })
          .catch(res=>{
            // 点击了取消

          });
      }else{
        this.currentForm.warehouseId = warehouse.warehouseId
        this.searchGoods()
      }
    },
    clearWaitConfirmMixin(){
      this.chooseWareGoodsMixinList.forEach(item=>{
        // 获取编辑的商品数量
        item.exGoodsMixinNum = this.mixinBoxGoodsList.filter(_item => _item.id === item.id)
          .reduce((prev,curr)=>{
            return prev + curr.boxGoodsNum
          },0)
      })
      this.chooseWareGoodsList = this.chooseWareGoodsList.filter(item => {
        return item.exGoodsMixinNum > 0 || item.exGoodsNumBox * item.goodsNumInBox > 0
      })

      // 官方仓清除未编辑数量
      this.chooseGoodsMixinList.forEach(item=>{
        item.exGoodsMixinNum = this.mixinBoxGoodsList.filter(_item => _item.id === item.id)
          .reduce((prev,curr)=>{
            return prev + curr.boxGoodsNum
          },0)
      })
      this.chooseGoodsList = this.chooseGoodsList.filter(item => {
        return item.exGoodsMixinNum > 0 || item.exGoodsNumBox * item.goodsNumInBox > 0
      })
    },
    // 改变了装箱数量
    changeFullGoodsList(row){

    },
    // 移仓箱子数据生成
    makeMoveWarehouseBoxList(){
      this.clearMoveWarehouseBoxList()
      this.chooseWareGoodsList.forEach(item=>{
        if(item.goodsNumInBox && item.exGoodsNumBox){
          for (let i = 0; i < item.exGoodsNumBox; i++) {
            const obj = deepCopy(item);
            obj.boxIndex = generateRandomString();
            obj.boxType = FULL_BOX;
            obj.logisticsNo = '';
            obj.estimateTime = '';
            obj.boxGoodsNum = item.goodsNumInBox;
            obj.editStatus = false
            obj.oldBoxId = ''
            this.moveWarehouseBoxList.push(obj)
          }
        }
      })
    },
    clearMoveWarehouseBoxList(){
      this.moveWarehouseBoxList = [];
    },
    // 混装数量需要重新生成
    clearMixinBoxGoodsList(){
      this.mixinBoxGoodsList = [];
    },
    // 更新了箱规
    updateBoxSize(row){
      const {suitId, weight, length, width, height, goodsNumInBox} = row
      this.currentGoodsList.filter(item => item.suitId === suitId)
        .forEach(item => {
          item.goodsNumInBox = goodsNumInBox
          item.boxAttr.weight = weight
          item.boxAttr.length = length
          item.boxAttr.width = width
          item.boxAttr.height = height
          item.boxAttr.goodsNumInBox = goodsNumInBox
        })

      this.chooseWareGoodsList.forEach(item => {
        if(item.suitId === suitId){
          item.goodsNumInBox = goodsNumInBox
          item.boxAttr.weight = weight
          item.boxAttr.length = length
          item.boxAttr.width = width
          item.boxAttr.height = height
          item.boxAttr.goodsNumInBox = goodsNumInBox
        }
      })
    },
    // 是否能编辑整箱
    canEditBoxNum(row){
      let flag = row.goodsNumInBox > 0 && row.boxAttr.weight > 0
      return flag
    },
    // 上传箱标
    uploadBoxPDFSuccess(file){
      this.currentForm.boxPDF = file
    },
    // 上传送仓单
    uploadAppointmentPDFSuccess(file){
      this.currentForm.appointmentPDF = file
    },
    chooseAddress(row){
      this.currentForm.address = deepCopy(row)
      this.currentForm.addressId = row.id
    }
  },
  // 路由跳转离开提示
  beforeRouteLeave(to,from,next){
    if(this.step > 1 && !this.isSubmit){
      setTimeout(()=>{
        this.$warning(this.$t('shipment.exitPageText'),{
          title: this.$t('shipment.exitPageTitle'),
        }).then(()=>{
          next();
        }).catch(() => {
          next(false);
        })
      },0)
    }else{
      next()
    }
  },


}
</script>

<style scoped lang="scss">
.wrap {
  padding: 20px 30px;

  .header {
    display: flex;
    justify-content: space-between;
  }

  .content {
    padding: 0px 0 0;
  }
  .step-tips{
    margin-top: 10px;
    font-size: 12px;
    color: #AAAAAA;
  }
  .step-content{

    .account-list{
      .haveGoodsButton{
        color: #67C23A;
        border-color: #67C23A;
        background-color: #f0f9eb;
      }
    }
    .goods-table{
      margin-top: 20px;
    }
    .box-card{
      background-color: #f2f2f2;
      font-weight: 500;
      .line{
        display: flex;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }
    .storageForm{
      margin-top: 30px;
    }
  }

  .full-shipment-box{
    .title{
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 5px;
    }
    .sub-title{
      font-size: 14px;
      color: #7f7f7f;
      margin-bottom: 5px;
    }
  }


  .footer{
    margin-top: 30px;
  }
}
.address-box{
  width: 400px;
  min-height: 100px;
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  border-radius: 5px;
  padding: 10px 10px 15px;
  .address-item{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    margin-top: 5px;
    font-size: 14px;
    .label{
      color: #AAAAAA;
      width: 80px;
    }
    .text{
      width: 300px;
    }
  }
}
</style>
